package com.djsearch.ui;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.protocol.RequestDate;
import org.json.JSONException;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;

import com.djsearch.R;
import com.djsearch.adapter.GroupShopListViewAdapter;
import com.djsearch.bean.GroupBuyGoods;
import com.djsearch.controller.AsyncHandler;
import com.djsearch.controller.IRequest;
import com.djsearch.controller.IResponse;
import com.djsearch.controller.JSONReq;
import com.djsearch.controller.JSONResp;
import com.djsearch.ui.GroupShopActivity.RequestParamStruct;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class SearchResultActivity extends BaseActivity{
	private Context mContext;
	private String newUrl;
	private String subjectName;
	private TextView subjectNameText;
	private Button backBtn;
	private List<GroupBuyGoods> nextPageGoodsList;//存放下一页请求的新数据
	private List<GroupBuyGoods> groupShopGoodsList;
	private GroupShopListViewAdapter groupShopListViewAdapter;
	private ListView goodsListView;
	private int PAGE = 1;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().requestFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.search_result_layout);
		mContext = this;
		Intent intent = getIntent();
		Bundle bundle = intent.getExtras();
		newUrl = bundle.getString("newUrl");
		subjectName = bundle.getString("subjectName");
		if (subjectName.equals("ktv")) {
			subjectName = "KTV" ;
		}
		nextPageGoodsList = new ArrayList<GroupBuyGoods>(); //更多（下一页数据）
		groupShopGoodsList = new ArrayList<GroupBuyGoods>();//当前页面数据
//		groupShopGoodsList = new ArrayList<GroupBuyGoods>();//当前页面数据
//		nextPageGoodsList = new ArrayList<GroupBuyGoods>(); //更多（下一页数据）
//		groupSortList = new ArrayList<String>();
//		saveGroupSortList = new ArrayList<String>();
		//初始化主界面
		initView();
		//初始化主界面相关点击事件
		initOnClick();
		//
		initHandler();
	}
	

	@Override
	void initHandler() {
		// TODO Auto-generated method stub
		
	}

	@Override
	void initView() {
		// TODO Auto-generated method stub
		subjectNameText = (TextView)findViewById(R.id.subjectName);
		subjectNameText.setText(subjectName);
		backBtn = (Button)findViewById(R.id.groupShopBackBtn);
		groupShopListViewAdapter = new GroupShopListViewAdapter(mContext,groupShopGoodsList);
		goodsListView = (ListView)findViewById(R.id.goodsListView);
		goodsListView.setAdapter(groupShopListViewAdapter);
		requestData();
	}

	private void requestData() {
		IRequest request = new JSONReq(newUrl,"","");
		request.putParam("queryByType", subjectName);
		request.putParam("page", String.valueOf(PAGE));
		request.putParam("pageNum", "10");
		HTTP.post(request, new AsyncHandler(){
			@Override
			public void onStart() {
//				showProgressBar(backBtn);
				showDialog("正在加载...");
				
			}
			@Override
			public void onSuccess(JSONResp response) {
				// TODO Auto-generated method stub
				int result = response.result();
				if(IResponse.Success==result){
					    PAGE++;
						getDataToResolve(response);
				} else if (IResponse.Fail==result) {
					//返回数据失败
					Toast.makeText(mContext, "没有数据", 5000).show();
				}
					missDialog();
			}
			@Override
			public void onFailure(Throwable e, String response) {
				// TODO Auto-generated method stub
//				super.onFailure(e, response);
				missDialog();
//				Log.e("GROUP", response);
				Toast.makeText(mContext, "网络传输错误", 5000).show();
//				missProgressBar();
			}
			
		});
	
	}


	@Override
	void initOnClick() {
		// TODO Auto-generated method stub
		backBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		
		
		/**
		 * 滑动到底部自动加载功能
		 */
		goodsListView.setOnScrollListener(new AbsListView.OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
				if ( scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
					if (view.getLastVisiblePosition() == (view.getCount() - 1)) {
						if (!(progressBarPopuWindow != null && progressBarPopuWindow.isShowing())) {
					        RequestParamStruct.page = PAGE;
					        requestData();
						}
					}
				}
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
			}
		});
		
		
		goodsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				startActivity(mContext, GroupShopDetailsActivity.class, 0, 
						groupShopGoodsList.get(position));
			}
		});
		
	}

	@Override
	void getDataToResolve(JSONResp response) {
		// TODO Auto-generated method stub

		try {
			Gson gson = new Gson();   
	        Type type = new TypeToken<List<GroupBuyGoods>>(){}.getType();  //指定集合对象属性  
	        List<GroupBuyGoods> fromJson = gson.fromJson(response.getString("returnMessage"), type); 
	        nextPageGoodsList.addAll(fromJson);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (nextPageGoodsList.size() == 0) {
				//当没有更多的数据了处理
			} else {
				groupShopGoodsList.addAll(nextPageGoodsList);
				nextPageGoodsList.clear();
			}
			groupShopListViewAdapter.refreshData(groupShopGoodsList);
		}
	}

}
